package com.bzyd.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.bzyd.cloud.dao.OrderDao;
import com.bzyd.cloud.dao.TxLogDao;
import com.bzyd.cloud.pojo.Order;
import com.bzyd.cloud.pojo.TxLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * Created by Xianyue Dang on 2021/8/20
 */
@Slf4j
@Service
public class OrderServiceImpl4 {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private TxLogDao txLogDao;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void createOrderBefore(Order order) {
        String txId = UUID.randomUUID().toString();
        //发送半事务消息
        String txProducerGroup = "tx_producer_group";
        String destination = "tx_topic";
        Message<Order> message = MessageBuilder.withPayload(order).setHeader("txId", txId).build();
        TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction(txProducerGroup, destination, message, order);
        log.info("发送half消失结果：{}", JSON.toJSONString(result));
        // 根据发送结果，决定是否报错回滚上一步的业务
    }

    //本地事务
    @Transactional
    public void createOrder(String txId, Order order) {
        //本地事务代码
        orderDao.save(order);
        //记录日志到数据库，回查使用
        TxLog txLog = new TxLog();
        txLog.setTxLogId(txId);
        txLog.setContent("事务测试");
        txLog.setDate(new Date());
        txLogDao.save(txLog);
    }
}
